﻿using Entity;
using ServiceCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Customer.Bussiness_Service
{

    public interface Imenu_service
    {
        ResultListModel<rk_menulist> get_pagelist(Base_List_Params query);
        ResultObjModel get_model(string mid);

        ResultModel save(rk_menu model);
        ResultModel del_item(string mid);
        ResultObjModel get_my_list(menu_type menu_type = menu_type.AdminWeb);
        ResultObjModel get_all_list(menu_type menu_type = menu_type.AdminWeb);
        ResultObjModel get_role_list(string role_id, menu_type menu_type = menu_type.AdminWeb); 
        ResultObjModel GetMenu(ref object idTolaber, string role_id = "", bool IsAll = false, menu_type menu_type = menu_type.AdminWeb);
    }
    public class menu_service : Imenu_service
    {
        private readonly IToole_DI _tool;
        public menu_service(IToole_DI Tool)
        {
            _tool = Tool;
        }
        #region 菜单
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<rk_menulist> get_pagelist(Base_List_Params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<rk_menulist>>(result =>
            {
                string sql = "select * from rk_menu";
                string where = " where 1=1 ";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrWhiteSpace(query.SerchKeyword))
                {
                    where += $" and m_name like @m_name";
                    query_dy.m_name = query.SerchKeyword;
                }
                result = _tool.di_db.GetPageList<rk_menulist>(sql, where, "addtime", query_dy, query.IsPage, query.page, query.pagesize);
                return result;
            });
        }
        /// <summary>
        /// 获取菜单详情
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_model(string mid)
        {
            ResultObjModel result = new ResultObjModel();
            try
            {
                var MenuModel = _tool.di_db.GetModel<rk_menu>(new string[] { "mid=@mid" }, new { mid = mid });
                if (MenuModel == null)
                {
                    result.code = 1;
                    result.msg = "菜单信息不存在";
                }
                else
                {
                    result.code = 0;
                    result.msg = "Success";
                    result.data = MenuModel;
                }
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultModel save(rk_menu model)
        {
            return CoreStartDo.ResultAction(result =>
            {
                #region  基础验证
                if (string.IsNullOrWhiteSpace(model.m_name))
                {
                    result.code = 1;
                    result.msg = "菜单名称不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.mid))
                {
                    model.mid = "";
                }
                var ExistModel = _tool.di_db.GetModel<rk_menu>(new string[] { "m_name=@m_name", "mid<>@mid", "ispage=@ispage" }, new { model.m_name, model.mid, ispage = true });
                if (ExistModel != null)
                {
                    result.code = 1;
                    result.msg = "菜单名称已存在";
                    return result;
                }
                #endregion
                #region 数据处理
                if (model.mid == "")
                {
                    //添加
                    model.mid = _tool.di_getid.IGet_SnowFlake_Id;
                    model.addtime = DateTime.Now;
                    model.adduser = "api_admin";
                    if (string.IsNullOrWhiteSpace(model.parent_id))
                    {
                        ///当前为最上级  这个就是自己
                        model.parent_id = "0";
                        model.mogami_id = model.mid;
                    }
                    else
                    {
                        var parentmodel = _tool.di_db.GetModel<rk_menu>(new string[] { "mid=@parent_id" }, new { model.parent_id });
                        if (parentmodel == null)
                        {
                            result.code = 1;
                            result.msg = "上级ID不存在";
                            return result;
                        }
                        else
                        {
                            model.mogami_id = parentmodel.mogami_id;
                        }
                    }
                    //默认是页面的 如果未来拓展到针对后台控制器,这里也能兼容使用
                    model.ispage = model.ispage.HasValue ? model.ispage.Value : true;
                    var resultCount = _tool.di_db.Add(model);
                    if (resultCount > 0)
                    {
                        result.code = 0;
                        result.msg = "添加成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "添加失败 DB error";
                    }
                }
                else
                {
                    //编辑
                    var needupdate = _tool.di_db.GetModel<rk_menu>(new string[] { "mid=@mid" }, new { model.mid });
                    if (needupdate == null)
                    {
                        result.code = 1;
                        result.msg = "修改信息不存在";
                        return result;
                    }
                    if (model.parent_id != needupdate.parent_id)
                    {
                        //糟糕 是心肌梗塞感觉。。。   好吧只是上级ID变了 重新获取一下
                        if (string.IsNullOrWhiteSpace(model.parent_id) || model.parent_id == "0")
                        {
                            ///当前为最上级  这个就是自己
                            model.parent_id = "0";
                            model.mogami_id = model.mid;
                        }
                        else
                        {

                            var parentmodel = _tool.di_db.GetModel<rk_menu>(new string[] { "mid=@parent_id" }, new { model.parent_id });
                            if (parentmodel == null)
                            {
                                result.code = 1;
                                result.msg = "上级ID不存在";
                                return result;
                            }
                            else
                            {
                                model.mogami_id = parentmodel.mogami_id;
                            }
                        }
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(model.parent_id) || model.parent_id == "0")
                        {
                            ///当前为最上级  这个就是自己
                            model.parent_id = "0";
                            model.mogami_id = model.mid;
                        }
                        else
                        {
                            var parentmodel = _tool.di_db.GetModel<rk_menu>(new string[] { "mid=@parent_id" }, new { model.parent_id });
                            if (parentmodel == null)
                            {
                                result.code = 1;
                                result.msg = "上级ID不存在";
                                return result;
                            }
                            else
                            {
                                model.mogami_id = parentmodel.mogami_id;
                            }
                        }
                    }
                    //默认是页面的 如果未来拓展到针对后台控制器,这里也能兼容使用
                    model.ispage = model.ispage.HasValue ? model.ispage.Value : true;
                    var resultCount = _tool.di_db.Update<rk_menu>(new string[] { "m_name", "route_url", "parent_id", "mogami_id", "ispage", "area", "controller", "action", "sort", "icon", "menu_type" }, new string[] { "mid=@mid" }
                     , new
                     {
                         model.m_name,
                         model.route_url,
                         model.icon,
                         model.parent_id,
                         model.mogami_id,
                         model.ispage,
                         model.area,
                         model.controller,
                         model.action,
                         model.sort,
                         model.mid,
                         model.menu_type
                     });
                    if (resultCount > 0)
                    {
                        result.code = 0;
                        result.msg = "修改成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "修改成功 DB error";
                    }
                }
                #endregion 
                return result;
            });
        }
        /// <summary>
        /// 删除菜单项
        /// </summary>
        /// <returns></returns>
        public ResultModel del_item(string mid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var resultCount = _tool.di_db.do_Execute("delete from rk_menu where mid=@mid", new { mid = mid });
                if (resultCount > 0)
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败,没有条目被改变";
                }

                return result;
            });
        }
        /// <summary>
        /// 获取当前用户权限列表
        /// </summary>
        /// <param name="role_id"></param>
        /// <returns></returns>
        public ResultObjModel get_my_list(menu_type menu_type = menu_type.AdminWeb)
        {
            object idTolaber = new object();
            return GetMenu(ref idTolaber, menu_type: menu_type);
        }
        /// <summary>
        /// 获取当前用户权限列表
        /// </summary>
        /// <param name="role_id"></param>
        /// <returns></returns>
        public ResultObjModel get_all_list(menu_type menu_type = menu_type.AdminWeb)
        {
            object idTolaber = new object();
            return GetMenu(ref idTolaber, IsAll: true, menu_type: menu_type);
        }
        /// <summary>
        /// 获取当前用户权限列表
        /// </summary>
        /// <param name="role_id"></param>
        /// <returns></returns>
        public ResultObjModel get_role_list(string role_id,menu_type menu_type = menu_type.AdminWeb)
        {
            object idTolaber = new object();
            return GetMenu(ref idTolaber, role_id, menu_type: menu_type);
        }
        /// <summary>
        /// 获取指定角色权限列表
        /// </summary>
        /// <returns></returns>
        public ResultObjModel GetMenu(ref object idTolaber, string role_id = "", bool IsAll = false, menu_type menu_type = menu_type.AdminWeb)
        {
            ResultObjModel result = new ResultObjModel();
            try
            {
                if (string.IsNullOrWhiteSpace(role_id))
                {
                    role_id = _tool.di_user.USER.role_id;
                }
                string serchsql = "";
                if (!IsAll)
                {
                    serchsql = $"select b.* from rk_role_menu a left join rk_menu b on a.mid = b.mid where 1=1 and a.rid = @rid and b.ispage=@ispage and b.menu_type=@menu_type";
                }
                else
                {
                    serchsql = $"select * from rk_menu where ispage=@ispage and menu_type=@menu_type";
                }
                List<rk_menu> myMenuList = _tool.di_db.GetList<rk_menu>(serchsql, new { rid = role_id, ispage = true, menu_type }).ToList();
                result.code = 0;
                result.msg = "Success";
                List<object> obj = new List<object>();
                result.data = GetMyMenulist(myMenuList, ref obj);
                idTolaber = obj; // from o in myMenuList select new { name = o.mid, title = o.m_name }; = 
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 获取我的菜单列表
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        private List<Vue_GetMyMenuList> GetMyMenulist(List<rk_menu> myMenuList, ref List<object> idTolaber)
        {
            List<Vue_GetMyMenuList> result = new List<Vue_GetMyMenuList>();
            if (myMenuList != null && myMenuList.Any())
            {
                foreach (var item in myMenuList.Where(s => s.parent_id == "0").OrderBy(s => s.sort))
                {
                    Vue_GetMyMenuList additem = new Vue_GetMyMenuList();
                    additem.name = item.mid;
                    additem.meta.title = item.m_name;
                    additem.meta.icon = item.icon;
                    additem.path = item.route_url;
                    if (!myMenuList.Where(s => s.parent_id == item.mid).Any())
                    {
                        additem.IsLast = true;
                        idTolaber.Add(new { name = item.mid, title = item.m_name });
                    }
                    else
                    {
                        additem.IsLast = false;
                    }
                    additem.children = GetNextList(myMenuList, item.mid, ref idTolaber);
                    result.Add(additem);
                }
            }
            return result;
        }
        private List<Vue_GetMyMenuList> GetNextList(List<rk_menu> myMenuList, string Parentid, ref List<object> idTolaber)
        {
            List<Vue_GetMyMenuList> result = new List<Vue_GetMyMenuList>();
            if (myMenuList.Where(s => s.parent_id == Parentid).Any())
            {
                foreach (var item in myMenuList.Where(s => s.parent_id == Parentid).OrderBy(s => s.sort))
                {
                    Vue_GetMyMenuList additem = new Vue_GetMyMenuList();
                    additem.name = item.mid;
                    additem.meta.title = item.m_name;
                    additem.meta.icon = item.icon;
                    additem.path = item.route_url;
                    if (!myMenuList.Where(s => s.parent_id == item.mid).Any())
                    {
                        additem.IsLast = true;
                        idTolaber.Add(new { name = item.mid, title = item.m_name });
                    }
                    else
                    {
                        additem.IsLast = false;
                    }
                    additem.children = GetNextList(myMenuList, item.mid, ref idTolaber);
                    result.Add(additem);
                }
            }
            return result;
        }
        #endregion
    }
}